package com.geelaro.register.config;

import com.geelaro.register.domain.entity.User;
import com.geelaro.register.service.CustomUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User.UserBuilder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.InMemoryTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;
import javax.swing.Spring;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private DataSource dataSource;

	@Autowired
	private CustomUserDetailService userDetailService;

	// 密码加密
	@Bean
	public BCryptPasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	// 自定义 认证规则
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {

		// 通常开发人员的WebSecurityConfigurerAdapter实现类在方法
		// public void configure(AuthenticationManagerBuilder builder) throws Exception
		// 中有如下调用 :
		// 这里 builder 是 AuthenticationManagerBuilder
		/*
		 * auth.jdbcAuthentication() .dataSource(dataSource)
		 * .passwordEncoder(passwordEncoder())
		 * .usersByUsernameQuery("select name,pass_wd from user where name=?")
		 * .authoritiesByUsernameQuery("select name, role from user_roles where username=?"
		 * );
		 */
		
		//将数据库查出的账户密码交给SpringSecurity去判断
		 auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());
	}

	// 授权
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable() // csrf不可用
				.authorizeRequests().antMatchers("/static/**", "/css/**", "/js/**").permitAll() // 访问允许静态文件
				.antMatchers("/", "/register").permitAll() // 允许访问首页和注册页

				//hasRole 框架会默认加上ROLE_，因此数据库中的权限应该定义为ROLE_xxx
				.antMatchers("/level1/**").hasRole("vip1") // level1下只有VIP1的人可以访问
				.antMatchers("/level2/**").hasRole("vip2")
				.antMatchers("/level3/**").hasRole("vip3")

				.anyRequest().authenticated()

				.and().formLogin().loginPage("/login").failureUrl("/login?error")// 指定登录页和登录失败页
				.defaultSuccessUrl("/index") // 登录成功跳转页
				.usernameParameter("name").passwordParameter("passWd")

				.and().logout().logoutSuccessUrl("/login").permitAll() // 退出登录跳转页

				.and().rememberMe() // remember me
				.tokenRepository(tokenRepository()) // 存储
				.userDetailsService(userDetailService).tokenValiditySeconds(24 * 60 * 60);// token有效期24h
	}

	public PersistentTokenRepository tokenRepository() {
		/** 存档到数据库中 **/
		JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
		db.setDataSource(this.dataSource);
		return db;
	}
}
